'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import GlassNavbar from '@/components/ui/GlassNavbar';
import GlassSidebar from '@/components/ui/GlassSidebar';
import ThemeToggle from '@/components/ui/ThemeToggle';
import {
  LayoutDashboard,
  FileText,
  FolderTree,
  Database,
  MessageSquare,
  Settings,
  Menu,
  ChevronLeft,
  LogOut,
  User,
  Users,
  Activity,
  ChevronDown,
  ChevronUp,
  Info,
  BookOpen,
} from 'lucide-react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { cn } from '@/lib/utils';
import { useAuthStore } from '@/store/authStore';
import ShLogo from '@/components/ui/ShLogo4';
import SidebarBrand from '@/components/ui/SidebarBrand';
import { authApi } from '@/lib/api';

// 菜单项分组
const menuGroups = [
  {
    name: '工作台',
    items: [
      { icon: LayoutDashboard, label: '仪表板', href: '/dashboard', roles: ['admin', 'manager', 'user'] },
      { icon: MessageSquare, label: 'RAG问答', href: '/dashboard/chat', roles: ['admin', 'manager', 'user'] },
    ]
  },
  {
    name: '内容管理',
    items: [
      { icon: FileText, label: '文档管理', href: '/dashboard/documents', roles: ['admin', 'manager', 'user'] },
      { icon: Database, label: '知识库', href: '/dashboard/knowledge-base', roles: ['admin', 'manager', 'user'] },
      { icon: BookOpen, label: '笔记中心', href: '/dashboard/notes', roles: ['admin', 'manager', 'user'] },
    ]
  },
  {
    name: '系统管理',
    items: [
      { icon: Users, label: '用户管理', href: '/dashboard/users', roles: ['admin'] },
      { icon: Activity, label: '系统监控', href: '/dashboard/monitoring', roles: ['admin'] },
      { icon: Settings, label: '系统维护', href: '/dashboard/system-maintenance', roles: ['admin'] },
      { icon: Settings, label: '系统设置', href: '/dashboard/settings', roles: ['admin'] },
    ]
  },
  {
    name: '帮助',
    items: [
      { icon: Info, label: '关于系统', href: '/dashboard/about', roles: ['admin', 'manager', 'user'] },
    ]
  },
];

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [userMenuOpen, setUserMenuOpen] = useState(false);
  // 默认收起所有分组
  const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(
    new Set(['工作台', '内容管理', '系统管理', '帮助'])
  );
  const pathname = usePathname();
  const router = useRouter();
  const { user, setUser, logout } = useAuthStore();

  // 确保用户信息已加载
  useEffect(() => {
    const loadUserInfo = async () => {
      if (!user) {
        try {
          const userInfo = await authApi.getCurrentUser();
          setUser(userInfo);
          console.log('[Dashboard] User info loaded:', userInfo);
        } catch (error) {
          console.error('[Dashboard] Failed to get user info:', error);
          router.push('/login');
        }
      }
    };
    loadUserInfo();
  }, [user, setUser, router]);

  // Filter menu groups based on user role
  const userRole = user?.role || 'user';
  const filteredMenuGroups = menuGroups
    .map(group => ({
      ...group,
      items: group.items.filter(item => 
        !item.roles || item.roles.length === 0 || item.roles.includes(userRole)
      )
    }))
    .filter(group => group.items.length > 0); // 只显示有权限项的分组
  
  console.log('[Dashboard Layout Debug]', {
    user: user,
    userRole: userRole,
    filteredMenuGroups: filteredMenuGroups.length,
    sidebarOpen: sidebarOpen
  });

  const handleLogout = () => {
    logout();
    router.push('/login');
  };

  const toggleGroup = (groupName: string) => {
    setCollapsedGroups(prev => {
      const next = new Set(prev);
      if (next.has(groupName)) {
        next.delete(groupName);
      } else {
        next.add(groupName);
      }
      return next;
    });
  };

  return (
    <div className="min-h-screen">
      {/* Navbar */}
      <GlassNavbar>
        <div className="flex items-center justify-between">
          {/* Left: Logo + Title */}
          <div className="flex items-center gap-3 pl-2">
            <ShLogo size={48} className="drop-shadow-lg" />
            <h1 className="text-2xl font-extrabold tracking-tight">
              <span className="bg-gradient-to-r from-indigo-600 via-purple-600 to-pink-600 bg-clip-text text-transparent dark:from-indigo-300 dark:via-purple-300 dark:to-pink-300 drop-shadow-sm">
                思和智库
              </span>
            </h1>
          </div>

          {/* Right: User menu + Theme toggle */}
          <div className="flex items-center gap-3 pr-6">
            <ThemeToggle />
            
            {/* User Dropdown Menu */}
            <div className="relative">
              <button
                onClick={() => setUserMenuOpen(!userMenuOpen)}
                className="flex items-center gap-2.5 glass px-4 py-2 rounded-2xl border border-indigo-200/40 dark:border-white/20 shadow-sm hover:shadow-md transition-all duration-300 hover:scale-105"
              >
                <User className="h-4 w-4 text-indigo-500 dark:text-white/80" />
                <span className="text-sm font-semibold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent dark:text-white/90">
                  {user?.username || 'Admin'}
                </span>
                <ChevronDown className={`h-4 w-4 text-indigo-500 dark:text-white/80 transition-transform ${userMenuOpen ? 'rotate-180' : ''}`} />
              </button>

              {/* Dropdown Content */}
              {userMenuOpen && (
                <>
                  {/* Backdrop with blur */}
                  <div 
                    className="fixed inset-0 z-40 bg-black/20 dark:bg-black/40 backdrop-blur-sm" 
                    onClick={() => setUserMenuOpen(false)}
                  />
                  
                  {/* Menu - Enhanced glassmorphism */}
                  <div className="absolute right-0 mt-2 w-56 rounded-2xl shadow-2xl z-50 overflow-hidden bg-white/90 dark:bg-gray-900/90 backdrop-blur-2xl backdrop-saturate-150 border border-gray-200/60 dark:border-white/30">
                    <div className="p-4 border-b border-indigo-200/30 dark:border-white/10">
                      <p className="text-xs text-gray-500 dark:text-white/50">登录身份</p>
                      <p className="font-semibold text-gray-900 dark:text-white">{user?.username}</p>
                      <p className="text-xs text-gray-500 dark:text-white/70">{user?.email || '未设置邮箱'}</p>
                    </div>
                    
                    <Link
                      href="/dashboard/profile"
                      className="flex items-center gap-3 px-4 py-3 hover:bg-gradient-to-r hover:from-indigo-50 hover:to-purple-50 dark:hover:bg-white/10 transition-all"
                      onClick={() => setUserMenuOpen(false)}
                    >
                      <User className="h-4 w-4 text-indigo-500 dark:text-white/80" />
                      <span className="text-sm font-medium text-gray-700 dark:text-white/90">个人设置</span>
                    </Link>
                    
                    <button
                      onClick={() => {
                        setUserMenuOpen(false);
                        handleLogout();
                      }}
                      className="w-full flex items-center gap-3 px-4 py-3 hover:bg-gradient-to-r hover:from-red-50 hover:to-pink-50 dark:hover:bg-white/10 transition-all border-t border-indigo-200/30 dark:border-white/10"
                    >
                      <LogOut className="h-4 w-4 text-red-500 dark:text-red-400" />
                      <span className="text-sm font-medium text-red-600 dark:text-red-400">退出登录</span>
                    </button>
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
      </GlassNavbar>

      {/* Sidebar */}
      <GlassSidebar isOpen={sidebarOpen}>
        {/* Sidebar Header with Brand and Toggle */}
        <div className="p-6 pb-4 border-b border-indigo-200/30 dark:border-white/10">
          <div className="flex items-center gap-3">
            {/* 能量点装饰区域 */}
            <div className="flex-1">
              <SidebarBrand />
            </div>
            
            {/* 收起按钮 */}
            <button
              onClick={() => setSidebarOpen(false)}
              className="glass p-2 rounded-xl hover:bg-gradient-to-br hover:from-indigo-50 hover:to-purple-50 dark:hover:bg-white/20 transition-all duration-300 hover:scale-105 group flex-shrink-0"
              title="收起侧边栏"
            >
              <ChevronLeft className="h-4 w-4 text-indigo-600 dark:text-white/80 group-hover:-translate-x-0.5 transition-transform" />
            </button>
          </div>
        </div>

        {/* Navigation Menu */}
        <div className="p-6 pt-4 space-y-4">
          {filteredMenuGroups.map((group, groupIndex) => {
            const isCollapsed = collapsedGroups.has(group.name);
            
            return (
              <div key={group.name}>
                {/* 分组标题（可折叠） */}
                <button
                  onClick={() => toggleGroup(group.name)}
                  className="w-full flex items-center justify-between px-4 py-2 mb-2 hover:bg-gradient-to-r hover:from-gray-100/50 hover:to-indigo-50/50 dark:hover:bg-white/5 rounded-lg transition-all"
                >
                  <h3 className="text-sm font-bold text-gray-600 dark:text-white/70 tracking-wide">
                    {group.name}
                  </h3>
                  {isCollapsed ? (
                    <ChevronDown className="h-4 w-4 text-gray-400 dark:text-white/50" />
                  ) : (
                    <ChevronUp className="h-4 w-4 text-gray-400 dark:text-white/50" />
                  )}
                </button>
                
                {/* 分组菜单项（可折叠） */}
                {!isCollapsed && (
                  <nav className="space-y-1">
                    {group.items.map((item) => {
                      const Icon = item.icon;
                      const isActive = pathname === item.href;
                      
                      return (
                        <Link
                          key={item.href}
                          href={item.href}
                          className={cn(
                            'flex items-center gap-3 px-4 py-3 rounded-xl',
                            'transition-all duration-300',
                            isActive
                              ? 'bg-gradient-to-r from-indigo-500/20 via-purple-500/20 to-pink-500/20 dark:bg-white/20 text-indigo-700 dark:text-white shadow-lg font-semibold border border-indigo-200/50 dark:border-white/30'
                              : 'text-gray-600 dark:text-white/80 hover:text-indigo-600 dark:hover:text-white hover:bg-gradient-to-r hover:from-gray-100/80 hover:to-indigo-50/80 dark:hover:bg-white/10 hover:scale-[1.02]'
                          )}
                        >
                          <Icon className="h-5 w-5" />
                          <span className="font-medium">{item.label}</span>
                        </Link>
                      );
                    })}
                  </nav>
                )}
              </div>
            );
          })}
        </div>
      </GlassSidebar>

      {/* Floating Menu Toggle Button (when sidebar is closed) */}
      {!sidebarOpen && (
        <button
          onClick={() => setSidebarOpen(true)}
          className="fixed top-20 left-4 z-50 glass p-3 rounded-2xl hover:bg-gradient-to-br hover:from-indigo-50 hover:to-purple-50 dark:hover:bg-white/20 transition-all duration-300 hover:scale-110 border border-indigo-200/40 dark:border-white/20 shadow-lg hover:shadow-xl"
          title="展开侧边栏"
        >
          <Menu className="h-5 w-5 text-indigo-600 dark:text-white/80" />
        </button>
      )}

      {/* Main content */}
      <main
        className={cn(
          'pt-20 transition-all duration-300',
          sidebarOpen ? 'ml-64' : 'ml-0'
        )}
      >
        <div className="p-8">
          {children}
        </div>
      </main>
    </div>
  );
}

